<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/16
 * Time: 15:50
 */
namespace Services;

use Admin\Models\school\XhschoolAutoclasserror;
use Helpers\Tool;
use Helpers\Main;
use Helpers\HttpClient;
use Helpers\XhException;

class UserService
{

    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;

    /**
     * 初始化配置
     *
     * @throws \Exception
     *
     * create by ck 20180507
     */
    private static function init()
    {
        if (!self::$httpClient) {
            $config     = Main::getConfigByName('user');
            self::$url  = Tool::getValue($config, 'url');
            if (!self::$url) {
                throw new \Exception('用户服务url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
        }
    }

    /**
     * 更改姓名
     *
     * @param $userId
     * @param $userName
     * @return bool
     * @throws XhException
     *
     * create by ck 20180724
     */
    public static function changeName($userId, $userName)
    {
        self::init();
        $response = self::$httpClient->post(
            sprintf('/api/v1/users/%d/nameChanged?userName=%s', $userId, urlencode($userName))
        );
        if (!$response->isSuccess()) {
            throw new XhException('姓名更改失败', $response);
        }
        return true;
    }

    /**
     * 根据家长id获取绑定学生信息
     *
     * @param $parentId
     * @throws XhException
     * @return array|bool|mixed|\stdClass
     *
     * create by ck 20180709
     */
    public static function getAssociationByParent($parentId)
    {
        self::init();
        $response = self::$httpClient->get(sprintf('/api/v1/users/%d/associations/children/', $parentId));
        if (!$response->isSuccess()) {
            throw new XhException('获取关联学生失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 取消学生-家长关联
     *
     * @param $parentId
     * @param $studId
     * @throws XhException
     * @return array|bool|mixed|\stdClass
     *
     * create by ck 20180709
     */
    public static function delAssociation($parentId, $studId)
    {
        self::init();
        $response = self::$httpClient->delete(
            sprintf('/api/v1/users/%d/associations/', $parentId),
            ['studentId' => $studId]
        );
        if (!$response->isSuccess()) {
            throw new XhException('取消关联失败', $response);
        }
        return true;
    }

    /**
     * 初始化学生班级
     *
     * @param $schoolId
     * @param $classInfo    --['className' => ['studId']]
     * @param $type         --0=行政班，1=培优班
     *
     * create by ck 20180711
     * modify by ck 20180712    可添加培优班
     * modify by ck 20180725    添加分组
     */
    public static function initStudClass($schoolId, $classInfo, $type = 0)
    {
        try {
            $classList  = self::getClass($schoolId);
            $existClass = $existFolder = [];
            foreach ($classList as $class) {
                if ($class['type'] == $type) {
                    if ($class['folder'] == false) {
                        $existClass[$class['id']] = $class['abbr'];
                    } else {
                        $existFolder[$class['id']] = $class['abbr'];
                    }
                }
            }

            foreach ($classInfo as $className => $studIds) {
                //不存在班级则创建
                $classId  = array_search($className, $existClass);
                $folderId = 0;
                if (!$classId) {
                    try {
                        $level      = substr($className, 0, 2);
                        $enrollYear = '20' . $level;

                        //行政班不存在分组则创建
                        if ($type == 0) {
                            try {
                                $folderName = $level . '级学生组';
                                $folderId   = array_search($folderName, $existFolder);
                                if (!$folderId) {
                                    $folder = self::createFolder($schoolId, $folderName, $enrollYear);
                                    $folderId = $folder['id'];
                                    $existFolder[$folderId] = $folderName;
                                }
                            } catch (XhException $e) {
                                (new XhschoolAutoclasserror())->create([
                                    'type' => 5,
                                    'schoolId' => $schoolId,
                                    'className' => $className,
                                    'classType' => $type,
                                    'msg' => $e->getMessage(),
                                    'description' => $e->getDescription(true),
                                ]);
                                continue;
                            }
                        }

                        $class = self::createClass($schoolId, $className, $enrollYear, $type, $folderId);
                        $classId = $class['id'];
                    } catch (XhException $e) {
                        (new XhschoolAutoclasserror())->create([
                            'type' => 1,
                            'schoolId' => $schoolId,
                            'className' => $className,
                            'classType' => $type,
                            'folderId' => $folderId,
                            'studIds' => $studIds,
                            'msg' => $e->getMessage(),
                            'description' => $e->getDescription(true),
                        ]);
                        continue;
                    }
                }

                //添加学生到行政班
                try {
                    self::addClassMember($schoolId, $classId, $studIds);
                } catch (XhException $e) {
                    (new XhschoolAutoclasserror())->create([
                        'type' => 3,
                        'schoolId' => $schoolId,
                        'className' => $className,
                        'classId' => $classId,
                        'classType' => $type,
                        'studIds' => json_encode($studIds),
                        'msg' => $e->getMessage(),
                        'description' => $e->getDescription(true),
                    ]);
                    continue;
                }
            }
        } catch (XhException $e) {
            (new XhschoolAutoclasserror())->create([
                'type' => 4,
                'schoolId' => $schoolId,
                'msg' => $e->getMessage(),
                'description' => $e->getDescription(true),
            ]);
        }
    }

    /**
     * 初始化教师班级
     *
     * @param $schoolId
     * @param $tchClass --['tchId'=>1,'subject'=>'语文','classNames'=>['1801']]
     *
     * create by ck 20180713
     */
    public static function initTchClass($schoolId, $tchClass)
    {
        try {
            $classList  = self::getClass($schoolId);
            $subjectEnum= ResBase::getDictionaries('subject');
            $existClass = [];
            foreach ($classList as $class) {
                if ($class['type'] == 0) {
                    $existClass[$class['id']] = $class['abbr'];
                }
            }

            foreach ($tchClass as $info) {
                foreach ($info['classNames'] as $className) {
                    $classId = array_search($className, $existClass);
                    if (!$classId) {
                        continue;
                    }

                    //判断科目是否存在
                    $subject = array_search($info['subject'], $subjectEnum);
                    if (!$subject) {
                        continue;
                    }

                    //加入行政班
                    try {
                        self::addClassTch($schoolId, $classId, $info['tchId'], $subject);
                    } catch (XhException $e) {
                        (new XhschoolAutoclasserror())->create([
                            'type' => 2,
                            'schoolId' => $schoolId,
                            'className' => $className,
                            'classId' => $classId,
                            'classType' => 0,
                            'tchId' => $info['tchId'],
                            'subject' => $info['subject'],
                            'msg' => $e->getMessage(),
                            'description' => $e->getDescription(true),
                        ]);
                        continue;
                    }
                }
            }
        } catch (XhException $e) {
            (new XhschoolAutoclasserror())->create([
                'type' => 4,
                'schoolId' => $schoolId,
                'msg' => $e->getMessage(),
                'description' => $e->getDescription(true),
            ]);
        }
    }

    /**
     * 根据学校id获取行政班
     *
     * @param $schoolId
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180710
     */
    public static function getClass($schoolId)
    {
        self::init();
        $response = self::$httpClient->get(sprintf('/api/v1/schools/%d/classes/', $schoolId));
        if (!$response->isSuccess()) {
            throw new XhException('获取行政班列表失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 创建行政班
     *
     * @param $schoolId
     * @param $name
     * @param $enrollYear
     * @param $type
     * @param $folderId
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180710
     * modify by ck 20180725    支持放入分组
     */
    public static function createClass($schoolId, $name, $enrollYear, $type = 0, $folderId = 0)
    {
        self::init();
        $response = self::$httpClient->postJson(sprintf('/api/v1/schools/%d/classes/', $schoolId), [
            'name'          => strval($name),
            'type'          => $type ? 'PEIYOU' : 'CLASSIC',
            'enrollYear'    => intval($enrollYear),
            'abbr'          => strval($name),
            'description'   => '',
            'folder'        => false,
            'number'        => 0,
            'parentId'      => $folderId,
        ]);
        if (!$response->isSuccess()) {
            throw new XhException('创建班级失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 创建行政班分组
     *
     * @param $schoolId
     * @param $name
     * @param $enrollYear
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180725
     */
    public static function createFolder($schoolId, $name, $enrollYear)
    {
        self::init();
        $response = self::$httpClient->postJson(sprintf('/api/v1/schools/%d/classes/', $schoolId), [
            'name'          => strval($name),
            'enrollYear'    => intval($enrollYear),
            'abbr'          => strval($name),
            'description'   => '',
            'folder'        => true,
            'number'        => 0,
            'parentId'      => 0,
        ]);
        if (!$response->isSuccess()) {
            throw new XhException('创建分组失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 加入学生到行政班
     *
     * @param $schoolId
     * @param $classId
     * @param $studIds
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180711
     */
    public static function addClassMember($schoolId, $classId, $studIds)
    {
        self::init();
        $response = self::$httpClient->postJson(
            sprintf('/api/v1/schools/%d/classes/%d/members/', $schoolId, $classId),
            $studIds
        );
        if (!$response->isSuccess()) {
            throw new XhException('学生加入班级失败', $response);
        }
        return true;
    }

    /**
     * 加入教师到行政班
     *
     * @param $schoolId
     * @param $classId
     * @param $tchId
     * @param $subject
     * @return bool
     * @throws XhException
     *
     * create by ck 20180713
     */
    public static function addClassTch($schoolId, $classId, $tchId, $subject)
    {
        self::init();
        $response = self::$httpClient->postJson(
            sprintf('/api/v1/schools/%d/classes/%d/teachers/import', $schoolId, $classId),
            ['subject' => strval($subject), 'teacherId' => $tchId]
        );
        if (!$response->isSuccess()) {
            throw new XhException('教师加入班级失败', $response);
        }
        return true;
    }

    /**
     * 强制修改用户密码（自动刷新登陆缓存）
     *
     * @param $userIds
     * @param $password
     * @param bool $alreadyMd5
     * @param bool $resetComplete
     * @return bool
     * @throws XhException
     * @throws \Exception
     *
     * create by ck 20180825
     */
    public static function resetPassword($userIds, $password, $alreadyMd5 = false, $resetComplete = false)
    {
        if (!$userIds) {
            throw new XhException('缺少用户id');
        }
        $userIds = is_array($userIds) ? $userIds : [$userIds];
        self::init();
        $password = $alreadyMd5 ? strtoupper($password) : strtoupper(md5($password));
        $response = self::$httpClient->putJson('/api/v1/users/password/force/reset', [
            'userIds'       => implode(',', $userIds),
            'newPassword'   => $password,
            'isResetStudentComplete' => $resetComplete
        ]);
        if (!$response->isSuccess()) {
            throw new XhException('修改密码失败', $response);
        }
        return true;
    }

    /**
     * 设置随机密码
     *
     * @param array $userIds
     * @param $time
     * @param string $pwd
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20181206
     */
    public static function setRandomPwd(array $userIds, $time, $pwd = '')
    {
        self::init();
        $userIds = array_map(function ($val) {
            return intval($val);
        }, $userIds);
        $response = self::$httpClient->postJson('/api/v1/users/password/random/set/', [
            'customPassword' => $pwd,
            'expiresTime' => $time,
            'userIdSet' => $userIds
        ]);
        if (!$response->isSuccess()) {
            throw new XhException('设置密码失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 清除随机密码
     *
     * @param array $userIds
     * @throws XhException
     *
     * create by ck 20181207
     * modify by ck 20181211    更改请求方式
     */
    public static function cleanRandomPwd(array $userIds)
    {
        self::init();
        $response = self::$httpClient->setQueryParams(['userIds' => implode(',', $userIds)])
            ->patch('/api/v1/users/password/random/remove/');
        if (!$response->isSuccess()) {
            throw new XhException('清除失败', $response);
        }
    }

    /**
     * 获取用户功能配置
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190212
     */
    public static function getUserConfigure()
    {
        self::init();
        $response = self::$httpClient->get('/api/v1/function/configs/');
        if (!$response->isSuccess()) {
            throw new XhException('获取失败', $response);
        }
        return $response->toArray();
    }


    /**
     * 获取某个用户配置
     *
     * @param $userId
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190212
     */
    public static function getUserConfigureByUserId($userId)
    {
        self::init();
        $response = self::$httpClient->get(sprintf("/api/v1/users/%d/function/configs/", $userId));
        if (!$response->isSuccess()) {
            throw new XhException('获取失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 添加或删除用户配置
     *
     * @param $userId
     * @param $key
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190213
     */
    public static function setUserConfigure($userId, $key)
    {
        self::init();
        $response = self::$httpClient->postJson(
            '/api/v1/users/function/configs/',
            ['userIds' => $userId, 'keys' => $key]
        );
        if (!$response->isSuccess()) {
            throw new XhException('设置失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 添加用户配置
     *
     * @param $name
     * @param $key
     * @param $description
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190213
     */
    public static function addUserConfigure($name, $key, $description)
    {
        self::init();
        $response = self::$httpClient->postJson(
            '/api/v1/function/configs/',
            ['name' => $name, 'key' => $key, 'description' => $description]
        );
        if (!$response->isSuccess()) {
            throw new XhException('添加失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 通过功能id获取配置详情
     *
     * @param $id
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * creat by sqb 20190213
     */
    public static function getUserConfigureByFuncId($id)
    {
        self::init();
        $response = self::$httpClient->get(sprintf("/api/v1/function/configs/%d", $id));
        if (!$response->isSuccess()) {
            throw new XhException('获取失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 更改用户配置
     *
     * @param $id
     * @param $description
     * @param $name
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190213
     */
    public static function modifyUserConfigureData($id, $description, $name)
    {
        self::init();
        $response = self::$httpClient->patchJson(sprintf("/api/v1/function/configs/%d", $id),
            ['description' => $description, 'name' => $name]
        );
        if (!$response->isSuccess()) {
            throw new XhException('获取失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 删除用户配置
     *
     * @param $id
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by sqb 20190214
     */
    public static function delUserConfigureByFuncId($id)
    {
        self::init();
        $response = self::$httpClient->delete(sprintf("/api/v1/function/configs/%d", $id));
        if (!$response->isSuccess()) {
            throw new XhException('删除失败', $response);
        }
        return $response->toArray();
    }
}
